#include "Form.h"
#include "login.h"
#include "ui_form.h"

#include <QMessageBox>
#include <qtextcodec.h>

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
}

Form::~Form()
{
    delete ui;
}

void Form::on_pushButton_2_clicked()
{
    login *l = new login();
    l->show();
    close();
}

void Form::on_btn_login_clicked()
{
    QTextCodec *codec = QTextCodec::codecForName("GB2312");
    if(QString::compare(ui->lineEdit_newpass->text(), ui->lineEdit_surepass->text()) == 0)
    {
        QString username = ui->lineEdit_newname->text();
        QString password = ui->lineEdit_newpass->text();
        QDir dir(qApp->applicationDirPath() + "/" + username);
        if(!dir.exists())
          {
           dir.mkdir(qApp->applicationDirPath() + "/" + username);
          }
        QVector<QString> temp;
        QFile file(qApp->applicationDirPath() + "/users.txt");


        if(file.open(QFile::ReadOnly | QIODevice::Text)){
            QTextStream out(&file);
            QString user_num = QString::number(codec->toUnicode(file.readLine()).toInt() + 1);
            qDebug() << user_num ;
            temp.push_back(user_num);
            while(!file.atEnd())
            {
                QString line = codec->toUnicode(file.readLine()).trimmed();
                qDebug() << line;
                temp.push_back(line);
            }
            file.close();
        }


        if(file.open(QFile::WriteOnly|QFile::Truncate|QIODevice::Text))
        {
            QTextStream out(&file);
            QString userInfo = username + " " + password;
            temp.push_back(userInfo);
            for (int i = 0; i < temp.size(); i++) {
                out << temp[i] << endl;
            }
        }
        file.close();
        QMessageBox MBox;
        MBox.setWindowTitle("提示信息");
        MBox.setText("注册成功");
        MBox.setIconPixmap(QPixmap(":/save.png").scaled(50,50));
        QPushButton *agreeBut = MBox.addButton("OK", QMessageBox::AcceptRole);
        MBox.exec();
    }else{
        QMessageBox::critical(this,"错误","密码输入不一致，请重试","确定");
    }

}

void Form::on_pushButton_clicked()
{
    close();
}


void Form::mousePressEvent(QMouseEvent *event)
{

     if( (event->button() == Qt::LeftButton) ){
         mouse_press = true;
         mousePoint = event->globalPos() - this->pos();
 //        event->accept();
    }
     else if(event->button() == Qt::RightButton){
         //如果是右键
        this->close();
     }
}
void Form::mouseMoveEvent(QMouseEvent *event)
{


 //    if(event->buttons() == Qt::LeftButton){  //如果这里写这行代码，拖动会有点问题
     if(mouse_press){
         move(event->globalPos() - mousePoint);
 //        event->accept();
     }
}
void Form::mouseReleaseEvent(QMouseEvent *event)
{
     mouse_press = false;
}
